import axios from "axios";
import { useTokenStore } from "@/stores/mytoken";
import { refreshToken } from "@/api/users";
import  router from "@/router/index";
  const request = axios.create({
     // baseURL: import.meta.env.VITE_API_URL,
  })
//请求拦截器
  request.interceptors.request.use((config) => {
    // 在请求发送之前做些什么
    if ( !config.headers) {
      config.headers = {} 
    }
    const store = useTokenStore()
    config.headers.Authorization = store.token?.access_token
    return config
  })

//响应拦截器

request.interceptors.response.use(
  (response) => response,
  async (error) => {
    if (error.response.status ===401){
      //刷新token
      const { data } = await refreshToken()
      if (data.success){
        //保存新toke/n
        useTokenStore().saveToken(data.content)
        //重新请求之前的接口，并且将结果返回
        return request(error.config)
      } else{
        //跳转到登录页面
        ElMessage.error("刷新token失败，请重新登录")
        
        router.push({ name: 'login' })
        return
      }
    } else if (error.response.status === 403){
      ElMessage.error("权限不足，请联系管理员")
      return { data: { code: "123456"}}
    }
    return Promise.reject(error)
  }
)

  export default request